import type { ContentItem } from '@/services'

export interface TreeNode extends ContentItem {
  children?: TreeNode[]
  isDirectory?: boolean
}

export function buildTreeData(data: ContentItem[]): TreeNode[] {
  const items = [...data]
  const rootNodes: TreeNode[] = []
  const nodeMap = new Map<string, TreeNode>()
  const directoryPaths = new Set<string>()

  // 收集所有目录路径
  items.forEach(item => {
    const pathParts = item.path.split('/').filter(Boolean)
    if (pathParts.length > 1) {
      // 添加所有可能的父目录路径
      let currentPath = ''
      for (let i = 0; i < pathParts.length - 1; i++) {
        currentPath = currentPath
          ? `${currentPath}/${pathParts[i]}`
          : pathParts[i]
        directoryPaths.add(currentPath)
      }
    }
  })

  // 创建所有节点（文件和目录）
  items.forEach(item => {
    const node: TreeNode = { ...item }
    nodeMap.set(node.path, node)
  })

  // 为目录路径创建目录节点
  directoryPaths.forEach(path => {
    if (!nodeMap.has(path)) {
      const dirNode: TreeNode = {
        path,
        title: path.split('/').pop() || '',
        isDirectory: true,
      }
      nodeMap.set(path, dirNode)
    }
  })

  // 构建树形结构
  nodeMap.forEach(node => {
    const pathParts = node.path.split('/').filter(Boolean)

    if (pathParts.length === 1) {
      // 根节点
      rootNodes.push(node)
    } else {
      // 获取父节点路径
      const parentPath = pathParts.slice(0, -1).join('/')
      const parent = nodeMap.get(parentPath)

      if (parent && parent.path !== node.path) {
        if (!parent.children) {
          parent.children = []
        }
        // 避免重复添加
        if (!parent.children.some(child => child.path === node.path)) {
          parent.children.push(node)
        }
      }
    }
  })

  // 递归排序所有节点
  const sortNodes = (nodes: TreeNode[]): TreeNode[] => {
    return nodes
      .sort((a, b) => {
        // 目录排在前面
        if (a.isDirectory && !b.isDirectory) return -1
        if (!a.isDirectory && b.isDirectory) return 1
        // 按字母顺序排序
        return a.date < b.date
      })
      .map(node => {
        if (node.children) {
          node.children = sortNodes(node.children)
        }
        return node
      })
  }

  return sortNodes(rootNodes)
}
